<template>
  <a-card class="general-card" title="会员列表" :bordered="false">
    <PickSearchColumn
      :columns="columnsSearch"
      @reset="
        (val) => {
          apiParams = { ...apiParams, ...val };
        }
      "
      @search="
        (val) => {
          apiParams = { ...apiParams, ...val };
        }
      "
    >
    </PickSearchColumn>
    <!-- <a-row style="margin-bottom: 16px" v-if="selectedMember">
      <a-col :span="16">
        <a-space>
          <a-button type="primary" @click="handleAdd"> 添加会员 </a-button>
        </a-space>
      </a-col>
    </a-row> -->
    <!--:api="getMemberListData"-->
    <!--:api-params="apiParams"-->
    <PickTablePage
      :dataList="membersList"
      ref="tablePageRef"
      :columns="columnsTable"
      :methods="sortMethods"
      :bordered="true"
      :enablePagination="false"
    >
      <template #orderDetail="{ data }" v-if="selectedMember">
        <a-button
          @click="handleMemberDetails(data)"
          type="text"
          status="success"
          >查看</a-button
        >
      </template>
      <!-- <template #editor="{ data }" v-if="selectedMember">
        <a-button @click="handleEdit(data)" type="text" status="warning">
          编辑
        </a-button>
      </template>
      <template #forbidden="{ data }" v-if="selectedMember">
        <a-button @click="handleForbidden(data)" type="text" status="danger">
          禁用
        </a-button>
      </template> -->
      <template #change="{ data }" v-else>
        <a-button
          @click="changUserList(data as Array<SomeEventType>)"
          type="text"
          :status="data.___selected ? 'danger' : ''"
          >{{ data.___selected ? '已选择' : '选择' }}</a-button
        >
      </template>
    </PickTablePage>
    <div class="paginationBox">
      <a-pagination
        :total="initData.total"
        :current="initData.number"
        :page-size="initData.size"
        show-page-size
        @change="
          (number) => {
            apiParams.pageNumber = number;
            init();
          }
        "
        @page-size-change="
          (number) => {
            apiParams.pageSize = number;
            init();
          }
        "
      ></a-pagination>
    </div>

    <!-- 添加modal -->
    <a-modal
      v-model:visible="memberData.enableAddModal"
      :align-center="false"
      :footer="false"
    >
      <template #title> 添加会员 </template>
      <a-form ref="formRef" :model="memberData.form" @submit="handleAddOk">
        <a-form-item
          field="username"
          label="会员名称"
          :rules="[REQUIRED, VARCHAR20]"
          :validate-trigger="['change']"
        >
          <a-input v-model="memberData.form.username" />
        </a-form-item>
        <a-form-item
          field="mobile"
          label="手机号码"
          :rules="[REQUIRED,MOBILE]"
          validate-phone
        >
          <a-input :max-length="11" v-model="memberData.form.mobile">
            <template #prepend> +86 </template>
          </a-input>
        </a-form-item>
        <a-form-item
          field="password"
          label="会员密码"
          :rules="[REQUIRED, VARCHAR255]"
        >
          <a-input-password  allow-clear :defaultVisibility="false" v-model="memberData.form.password" />
        </a-form-item>
        <a-form-item label="操作">
          <a-button
            :loading="memberData.formLoading"
            html-type="submit"
            type="primary"
            >保存</a-button
          >
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 修改会员modal -->
    <editModal ref="show" @init="init"></editModal>
  </a-card>
</template>

<script setup lang="ts">
import {
  addMember,
  getMemberInfoData,
  getMemberListData,
  updateMemberStatus,
} from '@/api/member';
import { PickSearchColumn,PickTablePage } from '@pickmall/ui-v3-components';

import useCurrentInstance from '@/hooks/useCurrentInstance';
import { ColumnsDataRule, MethodsRule, SearchRule } from '@/types/global';
import { md5 } from '@/utils/md5';
import { MOBILE, REQUIRED, VARCHAR20, VARCHAR255 } from '@/utils/validator';
import { Message } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { onMounted, reactive, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import editModal from './modal/index.vue';

const tablePageRef = ref<any>('');
const router = useRouter();
const formRef = ref<FormInstance>();

const show = ref(null) as any;
const emit = defineEmits<{ (e: 'callback', data: object): void }>();
interface formInterface {
  enableAddModal: boolean;
  formLoading: boolean;
  fid: string | number;
  form: {
    mobile: string;
    password: number | string;
    username: string;
  };
}
//  获取modal
const modal = useCurrentInstance().globalProperties?.$modal;
const selectedMember = ref<boolean>(true); // 是否显示按钮
const columnsSearch: Array<SearchRule> = [
  {
    label: '会员ID',
    model: 'id',
    disabled: false,
    input: true,
  },
  {
    label: '会员名称',
    model: 'username',
    disabled: false,
    input: true,
  },
  {
    label: '会员昵称',
    model: 'nickName',
    disabled: false,
    input: true,
  },
  {
    label: '联系方式',
    model: 'mobile',
    disabled: false,
    input: true,
  },
];

const columnsTable: ColumnsDataRule[] = [
  {
    title: '会员ID',
    dataIndex: 'id',
  },
  {
    title: '会员名称',
    dataIndex: 'username',
  },
  {
    title: '会员昵称',
    dataIndex: 'nickName',
    member:true
  },

  {
    title: '联系方式',
    dataIndex: 'mobile',
  },
  {
    title: '注册时间',
    dataIndex: 'createTime',
  },
  {
    title: '积分数量',
    dataIndex: 'points',
  },
];

const sortMethods: MethodsRule = {
  title: '操作',
  width: 300,
  fixed: 'right',
  methods: [
    {
      title: '查看',
      callback: 'orderDetail',
      slot: true,
      slotTemplate: 'orderDetail',
    },
    {
      title: '编辑',
      callback: 'editor',
      slot: true,
      slotTemplate: 'editor',
    },
    {
      title: '禁用',
      callback: 'forbidden',
      slot: true,
      slotTemplate: 'forbidden',
    },
    {
      title: '选择',
      callback: 'change',
      slot: true,
      slotTemplate: 'change',
    },
  ],
};

// 数据集
const memberData = reactive<formInterface>({
  enableAddModal: false,
  formLoading: false,
  fid: '', // 当前form的ids
  form: {
    mobile: '',
    username: '',
    password: '',
  }, // 表单提交数据
});

/**
 * 接收父组件传值
 */
const props = defineProps({
  // 已选择用户数据
  selectedList: {
    type: null,
    default: () => {
      return [];
    },
  },
});
const initData = ref<any>({
  total:0
});
const membersList = ref<Array<any>>([]);
const selectMember = ref<Array<any>>([]); // 保存选中的用户

// 将父级数据与当前组件数据进行匹配
const watchData = (data: any) => {
  membersList.value = data.map((item: any) => {
    item.___selected = false;
    if (selectMember.value.length !== 0) {
      selectMember.value.map((member: any) => {
        if (member.id === item.id) {
          item.___selected = true;
        }
        return member;
      });
    } else {
      item.___selected = false;
    }
    return item;
  });
};
const init = () => {
  getMemberListData(apiParams.value).then((res) => {
    if (res.data.success) {
      initData.value = res.data.result;
      watchData(res.data.result.records);
      // membersList.value = res.data.result.records.map(item => {
      //   if (selectMember.value.length !== 0) {
      //     selectMember.value.forEach(member => {
      //       if (member.id === item.id) {
      //         item.___selected = true;
      //       }
      //     })
      //   } else {
      //     item.___selected = false;
      //   }
      //   return item;
      // });
    }
  });
};

// 点击添加
function handleAdd() {
  memberData.enableAddModal = true;
  memberData.fid = '';
  memberData.form = {
    mobile: '',
    username: '',
    password: '',
  };
}
// 添加/修改编辑
async function handleAddOk() {
  const params = {
    ...memberData.form,
    password: md5(memberData.form.password),
  };
  const auth = await formRef.value?.validate();
  if (!auth) {
    const res = !memberData.fid ? await addMember(JSON.parse(JSON.stringify(params))) : '';
    if (res && res.data.success) {
      Message.success(`${memberData.fid ? '修改' : '添加'}成功!`);
      memberData.enableAddModal = false;
      init();
    }
  }
}

// 编辑回显
function handleEdit(val: any) {
  getMemberInfoData(val.id).then((res: any) => {
    if (res.data.code == 200) {
      show.value.editMemberModal.data = res.data.result;
    }
  });
  show.value.descFlag = true;
}

// 回调禁用
function handleForbidden(data: any) {
  const params = {
    memberIds: data.id,
    disabled: false,
  };

  modal.confirm({
    title: '提示',
    content: '确认禁用此会员？',
    alignCenter: false,
    onOk: async () => {
      const res = await updateMemberStatus(params);
      if (res.data.success) {
        Message.success('禁用成功');
        membersList.value = [];
        init();
      }
    },
  });
}
// 查看
const handleMemberDetails = (data: any) => {
  router.push({ name: 'member-detail', query: { id: data.id } });
  // window.open(url.href, '_blank');
  localStorage.setItem('memberID', data.id);
};

const apiParams = ref({
  disabled: 'OPEN',
  pageNumber: 1, // 当前页数
  pageSize: 10, // 页面大小
  sort: 'createTime', // 默认排序字段
  order: 'desc', // 默认排序方式
});

const changUserList = (val: any): void => {
  val.___selected = !val.___selected;
  // selectMember.value.forEach(item=>{item.___selected = false});
  let findUser = selectMember.value.find((item: any) => {
    return item.id === val.id;
  }) as any;
  if (findUser && findUser.id) {
    // 有重复数据就删除
    selectMember.value.map((item: any, index: number) => {
      if (item.id === findUser.id) {
        selectMember.value.splice(index, 1);
      }
    });
  } else {
    // 如果没有则添加
    selectMember.value.push(val);
  }
  emit('callback', val);
};
defineExpose({
  selectedMember,
  sortMethods,
});
onMounted(() => {
  init();
});
watch(
  () => [props.selectedList],
  (val: any) => {
    selectMember.value = JSON.parse(JSON.stringify(val))[0];
    watchData(membersList.value);
  },
  { deep: true }
);
watch(
  () => [apiParams],
  (val) => {
    init();
  },
  { deep: true }
);
</script>

<style lang="less" scoped>
.face {
  width: 60px;
  height: 60px;
  border-radius: 50%;
}

.edit {
  margin-left: 10px;
}
.paginationBox {
  margin-top: 18px;
  display: flex;
  flex-direction: row-reverse;
}
</style>
